package com.px.web.controller.system;

import cn.hutool.json.JSONArray;
import com.px.common.annotation.Log;
import com.px.common.constant.Constants;
import com.px.common.core.controller.BaseController;
import com.px.common.core.domain.AjaxResult;
import com.px.common.core.domain.entity.SysUser;
import com.px.common.core.domain.model.LoginUser;
import com.px.common.core.page.TableDataInfo;
import com.px.common.enums.BusinessType;
import com.px.common.utils.SecurityUtils;
import com.px.common.utils.StringUtils;
import com.px.device.domain.RoutesInfo;
import com.px.device.service.IDroneInfoService;
import com.px.device.service.IRoutesInfoService;
import com.px.framework.aes.AesSecurityParameter;
import com.px.framework.manager.AsyncManager;
import com.px.framework.manager.factory.AsyncFactory;
import com.px.framework.web.service.SysLoginService;
import com.px.framework.web.service.TokenService;
import com.px.plan.domain.*;
import com.px.plan.service.*;
import com.px.system.domain.DroneInfo;
import com.px.system.domain.vo.AppVo;
import com.px.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Api("App接口")
@RestController
@RequestMapping("/app")
public class AppController extends BaseController {

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private IDroneInfoService droneInfoService;
    @Autowired
    private IPlanActionRecordService actionRecordService;
    @Autowired
    private IPlanActionService planActionService;
    @Autowired
    private IPlanActionRecordService planActionRecordService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IPlanActionSchemeService planActionSchemeService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IPlanActionMarkService planActionMarkService;

    @Autowired
    private IRoutesInfoService routesInfoService;


    @ApiOperation("App登录接口")
    @PostMapping("/login")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult appLogin(@RequestBody AppVo appVo)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.appLogin(appVo.getUsername(), appVo.getPassword());
        ajax.put(Constants.TOKEN, token);
//        droneInfoService.bindingSn(appVo);
        return ajax;
    }

    @ApiOperation("设备上下线接口")
    @PostMapping("/online")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult online(@RequestBody AppVo appVo)
    {
        droneInfoService.online(appVo);
        return AjaxResult.success();
    }

    @ApiOperation("设备信息注册更新接口")
    @PostMapping("/registerOrUpdate")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult registerOrUpdate(@RequestBody DroneInfo droneInfo)
    {
        return toAjax(droneInfoService.registerOrUpdate(droneInfo));
    }

    /**
     * 我的飞行行动列表
     */
    @ApiOperation("我的飞行行动列表")
    @GetMapping("/action/myList")
    @AesSecurityParameter(outEncode = true)
    public TableDataInfo myList()
    {
        PlanAction planAction = new PlanAction();
        planAction.setPilotId("," + getUserId() + ",");
        List<PlanAction> list = planActionService.selectPlanActionList(planAction);
        return getDataTable(list);
    }

    /**
     * 我的飞行记录列表
     */
    @ApiOperation("我的飞行记录列表")
    @GetMapping("/action/myRecordList")
    @AesSecurityParameter(outEncode = true)
    public TableDataInfo myRecordList()
    {
        PlanActionRecord record = new PlanActionRecord();
        record.setPilotId(getUserId());
        List<PlanActionRecord> planActionRecords = planActionRecordService.selectPlanActionRecordList(record);
        return getDataTable(planActionRecords);
    }

    /**
     * 飞行行动详情
     */
    @ApiOperation("飞行行动详情")
    @GetMapping(value = "/action/{id}")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(planActionService.selectPlanActionById(id));
    }

    @ApiOperation("行动参与")
    @Log(title = "行动参与", businessType = BusinessType.UPDATE)
    @PostMapping("/action/join")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult join(@RequestBody PlanActionRecord record)
    {
        Assert.notNull(record.getActionId(), "请传入行动ID");
        Assert.hasLength(record.getDroneSn(), "请传入无人机SN");
        Long recordId = actionRecordService.getRecordId(record.getActionId(), record.getDroneSn());
        return AjaxResult.success(recordId);
    }

    /**
     * 获取行动方案详细信息
     */
    @ApiOperation("获取行动方案详细信息")
    @GetMapping(value = "/scheme/{id}")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult getSchemeInfo(@PathVariable("id") Long id)
    {
        PlanActionScheme planActionScheme = planActionSchemeService.selectPlanActionSchemeById(id);
        planActionScheme.setPlanMarkFormList(new JSONArray(planActionScheme.getPlanMarkList()));
        planActionScheme.setPlanModelFormList(new JSONArray(planActionScheme.getPlanModelList()));
        return success(planActionScheme);
    }

    @ApiOperation("退出登录")
    @PostMapping("/logout")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult logout(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginAppUser(loginUser.getToken(), loginUser.getUser().getUserId());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
        }
        return AjaxResult.success("退出成功");
    }

    @ApiOperation("获取用户信息")
    @GetMapping("getInfo")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        AjaxResult ajax = AjaxResult.success();
        ajax.put("name", user.getNickName());
        ajax.put("phoneNumber", user.getPhonenumber());
        return ajax;
    }

    @ApiOperation("修改密码")
    @PostMapping("/updatePwd")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult updatePwd(@RequestBody AppVo appVo)
    {
        LoginUser loginUser = getLoginUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(appVo.getOldPassword(), password))
        {
            return error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(appVo.getNewPassword(), password))
        {
            return error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(appVo.getNewPassword())) > 0)
        {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(appVo.getNewPassword()));
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }

    /**
     * 查询飞行行动标记列表
     */
    @ApiOperation("查询飞行行动标记列表")
    @GetMapping("/mark/{id}")
    @AesSecurityParameter(outEncode = true)
    public TableDataInfo list(@PathVariable("id") Long id)
    {
        PlanActionMark planActionMark = new PlanActionMark();
        planActionMark.setActionId(id);
        List<PlanActionMark> list = planActionMarkService.selectPlanActionMarkList(planActionMark);
        return getDataTable(list);
    }

    /**
     * 查询航线列表
     */
    @ApiOperation("查询航线列表")
    @GetMapping("/getRoutesList")
    @AesSecurityParameter(outEncode = true)
    public TableDataInfo getRoutesList()
    {
        List<RoutesInfo> list = routesInfoService.getRoutesListByUserId(getUserId());
        return getDataTable(list);
    }


}
